<?php
namespace App\Libs\Base;
class BaseDispatcher extends \Phalcon\Mvc\Dispatcher
{
    public function dispatch()
    {
        // This is executed before every found action
        $namespace = '\\App\\Controllers';
        $controllerName = $this->getControllerName();
        $actionName = $this->getActionName();
        $actionClass = $namespace . '\\' . ucfirst($controllerName);
        // .html 
        $html = FALSE;
        if (substr($actionName, strlen($actionName) - 5) === '.html') {
            $actionClass .= '\\Page';
            $actionName = substr($actionName, 0, strlen($actionName) - 5);
            $html = TRUE;
        }

        if ($actionName !== '') {
            $actionClass .= '\\' . ucfirst($actionName);
        }
        $action = NULL;
        if (class_exists($actionClass)) {
            $action = new $actionClass($this->getDi());
            if ($action instanceof BaseTwigAction) {
                $action->setCategory($controllerName);
                $action->setPage($actionName);
                $action->run();
            } else if ($action instanceof BaseAction) {
                $action->run();
            } else {
                header('HTTP/1.0 404 Not Found');
            }
        } else if($html) {
            $action = new BaseTwigAction($this->getDi());
            $action->setCategory($controllerName);
            $action->setPage($actionName);
            $action->run();
        } else {
            header('HTTP/1.0 404 Not Found');
        }
        return $action;
    }

}
